package cz.data.common.jackson;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import cz.data.common.utils.SecurityModuleUtil;

import java.io.IOException;

public class ObjectJsonSerializer extends JsonSerializer<Object> {
    public static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void serialize(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String value = objectMapper.writer().writeValueAsString(obj);
        jsonGenerator.writeString(value);
    }

    static {
        SecurityModuleUtil.registerJavaTimeModule(objectMapper);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    }

}
